import React from 'react'
import { AppBar, Toolbar, IconButton, Avatar, Menu, MenuItem, Typography } from '@material-ui/core'
import { Menu as MenuIcon, AccountCircle as AccountCircleIcon } from '@material-ui/icons'
import styled from 'styled-components'

const StyledTypography = styled(Typography)`
  flex-grow: 1;
`

interface Props {
  handleToggleMenu: () => void;
  handleLogout: () => void;
}

const AppBarBase: React.FC<Props> = (props) => {
  const [anchorEl, setAnchorEl] = React.useState<HTMLButtonElement | null>(null)
  const open = Boolean(anchorEl)

  function handleMenuOpen (e: React.MouseEvent<HTMLButtonElement>): void {
    setAnchorEl(e.currentTarget)
  }

  function handleMenuClose (): void {
    setAnchorEl(null)
  }

  const renderAvatar = (): React.ReactNode => {
    return (
      <div>
        <IconButton onClick={handleMenuOpen} color="inherit">
          <AccountCircleIcon />
        </IconButton>
        <Menu
          id="menu-appbar"
          anchorEl={anchorEl}
          anchorOrigin={{
            vertical: 'top',
            horizontal: 'right',
          }}
          keepMounted
          transformOrigin={{
            vertical: 'top',
              horizontal: 'right',
          }}
          open={open}
          onClose={handleMenuClose}
        >
          <MenuItem onClick={handleMenuClose}>Profile</MenuItem>
          <MenuItem onClick={props.handleLogout}>Logout</MenuItem>
        </Menu>
      </div>
    )
  }

  return (
    <AppBar position="absolute">
      <Toolbar>
        <IconButton onClick={props.handleToggleMenu} edge="start" color="inherit">
          <MenuIcon />
        </IconButton>
        <StyledTypography variant="h6">
          MATERIAL-DASHBOARD-PRO
        </StyledTypography>
        {renderAvatar()}
      </Toolbar>
    </AppBar>
  )
}

export default AppBarBase
